class Request {
	// 设置全局默认配置
	setConfig(customConfig) {
		// 合并对象
		this.config = Object.assign(this.config, customConfig);
	}

	// 主要请求部分
	request(options = {}) {
		// 检查请求拦截
		if (this.interceptor.request && typeof this.interceptor.request === 'function') {
			let tmpConfig = {};
			let interceptorRequest = this.interceptor.request(options);
			if (interceptorRequest === false) {
				// 返回一个处于pending状态中的Promise，来取消原promise，避免进入then()回调
				return new Promise(() => {});
			}
			options = interceptorRequest;
		}
		options.url = options.url || '';
		options.data = options.data || {};
		options.method = options.method || this.config.method;
		options.header = Object.assign({}, this.config.header, options.header);
		options.dataType = options.dataType || this.config.dataType;
		options.responseType = options.responseType || this.config.responseType;

		return new Promise((resolve, reject) => {
			options.complete = (response) => {
				if (response.statusCode == 200) {
					if (this.interceptor.response && typeof this.interceptor.response === 'function') {
						let resInterceptors = this.interceptor.response(response.data);
						if (resInterceptors !== false) {
							resolve(resInterceptors);
						} else {
							reject(response.data);
						}
					} else {
						// 如果不是返回原始数据(originalData=false)，且没有拦截器的情况下，返回纯数据给then回调
						resolve(response.data);
					}
				} else {
					reject(response)
				}
			}

			// 判断用户传递的URL是否http或/开头,如果不是,加上/
			const httpReg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?/;
			if (httpReg.test(options.url)) {
				options.url = options.url;
			} else {
				const uri = options.url.indexOf('/') == 0 ? options.url : '/' + options.url;
				options.url = this.config.baseUrl + uri;
			}

			uni.request(options);
		});
	}

	constructor() {
		this.config = {
			baseUrl: '', // 请求的根域名
			// 默认的请求头
			header: {},
			method: 'POST',
			// 设置为json，返回后uni.request会对数据进行一次JSON.parse
			dataType: 'json',
			// 此参数无需处理，因为5+和支付宝小程序不支持，默认为text即可 arraybuffer
			responseType: 'text',
		}

		// 拦截器
		this.interceptor = {
			// 请求前的拦截
			request: null,
			// 请求后的拦截
			response: null
		}

		// get请求
		this.get = (url, data = {}, header = {}) => {
			return this.request({
				method: 'GET',
				url,
				header,
				data
			})
		}

		// post请求
		this.post = (url, data = {}, header = {}) => {
			return this.request({
				url,
				method: 'POST',
				header,
				data
			})
		}

		// put请求，不支持支付宝小程序(HX2.6.15)
		this.put = (url, data = {}, header = {}) => {
			return this.request({
				url,
				method: 'PUT',
				header,
				data
			})
		}

		// delete请求，不支持支付宝和头条小程序(HX2.6.15)
		this.delete = (url, data = {}, header = {}) => {
			return this.request({
				url,
				method: 'DELETE',
				header,
				data
			})
		}
	}
}

export default new Request
